// pages/user/profile/profile.js
const app = getApp();

Page({
  data: {
    user: null,
    loading: false,
    showEditModal: false,
    currentField: '',
    currentFieldTitle: '',
    editValue: '',
    genderText: '未设置'
  },

  onLoad() {
    this.fetchUserInfo();
  },

  onShow() {
    // 只在首次进入时显示loading
    if (!this.data.user) {
      this.fetchUserInfo();
    }
  },

  onPullDownRefresh() {
    this.fetchUserInfo(true);
  },

  // 获取用户信息
  async fetchUserInfo(fromPullDown = false) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      });
      return;
    }

    if (!fromPullDown) this.setData({ loading: true });

    try {
      const res = await app.request({ url: '/api/auth/me', method: 'GET' });
      if (res.statusCode === 200 && res.data) {
        const payload = res.data.data || null;
        const user = payload && payload.user ? payload.user : payload;
        
        if (user) {
          // 处理性别显示
          const genderText = this.getGenderText(user.gender);
          this.setData({ 
            user, 
            genderText 
          });
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    } finally {
      if (fromPullDown) wx.stopPullDownRefresh();
      this.setData({ loading: false });
    }
  },

  // 显示骨架屏并刷新数据
  async showSkeletonAndRefresh() {
    // 先显示骨架屏
    this.setData({ loading: true });
    
    // 并行执行：1秒等待 + 数据获取
    const [_, userData] = await Promise.all([
      new Promise(resolve => setTimeout(resolve, 1000)), // 固定等待1秒
      this.fetchUserInfoSilently() // 同时获取数据
    ]);
    
    // 1秒后隐藏骨架屏，无论数据是否已获取完成
    this.setData({ loading: false });
  },

  // 静默更新用户信息，不显示loading状态
  async fetchUserInfoSilently() {
    const token = wx.getStorageSync('token');
    if (!token) {
      return;
    }

    try {
      const res = await app.request({ url: '/api/auth/me', method: 'GET' });
      if (res.statusCode === 200 && res.data) {
        const payload = res.data.data || null;
        const user = payload && payload.user ? payload.user : payload;
        
        if (user) {
          // 处理性别显示
          const genderText = this.getGenderText(user.gender);
          this.setData({ 
            user, 
            genderText 
          });
        }
      }
    } catch (error) {
      // 静默处理错误，不影响用户体验
      console.error('静默更新用户信息失败:', error);
    }
  },

  // 获取性别文本
  getGenderText(gender) {
    switch (gender) {
      case 1: return '男';
      case 2: return '女';
      default: return '未设置';
    }
  },

  // 点击头像
  onAvatarTap() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.uploadAvatar(res.tempFilePaths[0]);
      }
    });
  },

  // 复制用户ID
  onCopyUserId() {
    const userId = this.data.user && this.data.user.id;
    if (userId) {
      wx.setClipboardData({
        data: userId.toString(),
        success: () => {
          wx.showToast({
            title: '已复制到剪贴板',
            icon: 'none',
            duration: 1500
          });
        }
      });
    } else {
      wx.showToast({
        title: '用户ID不存在',
        icon: 'none'
      });
    }
  },

  // 上传头像
  async uploadAvatar(filePath) {
    wx.showLoading({ title: '上传中...' });

    try {
      const uploadRes = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: app.globalData.apiBase + '/api/auth/updateProfile',
          filePath: filePath,
          name: 'avatar',
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        });
      });

      if (uploadRes.statusCode === 200) {
        const data = JSON.parse(uploadRes.data);
        console.log('头像上传返回数据:', data);
        if (data.success) {
          // 获取新的头像URL
          let avatarUrl = data.data.user.avatar;
          
          console.log('新头像URL:', avatarUrl);
          
          // 强制刷新：先清空头像，再设置新头像
          this.setData({ 
            user: { ...this.data.user, avatar: '' } 
          }, () => {
            // 延迟一点点再设置新头像，确保视图刷新
            setTimeout(() => {
              this.setData({ 
                user: { ...this.data.user, avatar: avatarUrl } 
              }, () => {
                console.log('头像已更新到data:', this.data.user.avatar);
              });
            }, 50);
          });
          
          wx.showToast({
            title: '头像更新成功',
            icon: 'none',
            duration: 1500
          });
        } else {
          throw new Error(data.message || '上传失败');
        }
      } else {
        throw new Error('上传失败');
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 点击编辑字段
  onEditField(e) {
    const field = e.currentTarget.dataset.field;
    const fieldTitles = {
      name: '姓名',
      phone: '账号',
      email: '邮箱',
      gender: '性别',
      birthday: '生日',
      height: '身高',
      target_weight: '目标体重'
    };

    let currentValue = '';
    if (this.data.user) {
      switch (field) {
        case 'name':
          currentValue = this.data.user.name || '';
          break;
        case 'phone':
          currentValue = this.data.user.phone || '';
          break;
        case 'email':
          currentValue = this.data.user.email || '';
          break;
        case 'gender':
          currentValue = this.data.user.gender;
          break;
        case 'birthday':
          currentValue = this.data.user.birthday || '';
          break;
        case 'height':
          currentValue = this.data.user.height || '';
          break;
        case 'target_weight':
          currentValue = this.data.user.target_weight || '';
          break;
      }
    }

    this.setData({
      showEditModal: true,
      currentField: field,
      currentFieldTitle: fieldTitles[field],
      editValue: currentValue
    });
  },

  // 输入框变化
  onInputChange(e) {
    this.setData({
      editValue: e.detail.value
    });
  },

  // 性别选择
  onGenderSelect(e) {
    const value = parseInt(e.currentTarget.dataset.value);
    this.setData({
      editValue: value
    });
  },

  // 日期选择
  onDateChange(e) {
    this.setData({
      editValue: e.detail.value
    });
  },

  // 关闭弹窗
  onModalClose() {
    this.setData({
      showEditModal: false,
      currentField: '',
      currentFieldTitle: '',
      editValue: ''
    });
  },

  // 点击弹窗内容区域（阻止冒泡）
  onModalContentTap() {
    // 阻止事件冒泡，防止关闭弹窗
  },

  // 保存字段
  async onSaveField() {
    const { currentField, editValue } = this.data;
    
    // 验证输入
    if (!this.validateField(currentField, editValue)) {
      return;
    }

    wx.showLoading({ title: '保存中...' });

    try {
      const updateData = {};
      updateData[currentField] = editValue;

      const res = await app.request({
        url: '/api/auth/updateProfile',
        method: 'POST',
        data: updateData
      });

      if (res.statusCode === 200 && res.data && res.data.success) {
        // 更新本地用户信息
        const user = { ...this.data.user, ...updateData };
        const genderText = this.getGenderText(user.gender);
        
        this.setData({ 
          user, 
          genderText,
          showEditModal: false,
          currentField: '',
          currentFieldTitle: '',
          editValue: ''
        });

        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500
        });
      } else {
        throw new Error(res.data?.message || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 验证字段
  validateField(field, value) {
    switch (field) {
      case 'name':
        if (!value || value.trim().length === 0) {
          wx.showToast({ title: '请输入姓名', icon: 'none' });
          return false;
        }
        if (value.trim().length > 20) {
          wx.showToast({ title: '姓名不能超过20个字符', icon: 'none' });
          return false;
        }
        break;
      
      case 'phone':
        if (!value || value.trim().length === 0) {
          wx.showToast({ title: '请输入账号', icon: 'none' });
          return false;
        }
        if (!/^1[3-9]\d{9}$/.test(value.trim())) {
          wx.showToast({ title: '请输入正确的账号', icon: 'none' });
          return false;
        }
        break;
      
      case 'email':
        if (value && value.trim().length > 0) {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(value.trim())) {
            wx.showToast({ title: '请输入正确的邮箱格式', icon: 'none' });
            return false;
          }
        }
        break;
      
      case 'gender':
        if (value === '' || value === null || value === undefined) {
          wx.showToast({ title: '请选择性别', icon: 'none' });
          return false;
        }
        break;
      
      case 'birthday':
        if (value && value.trim().length > 0) {
          const date = new Date(value);
          const now = new Date();
          if (date > now) {
            wx.showToast({ title: '生日不能是未来日期', icon: 'none' });
            return false;
          }
        }
        break;
      
      case 'height':
        if (value && value.toString().trim().length > 0) {
          const height = parseFloat(value);
          if (isNaN(height) || height <= 0) {
            wx.showToast({ title: '请输入正确的身高', icon: 'none' });
            return false;
          }
          if (height < 50 || height > 250) {
            wx.showToast({ title: '身高范围应在50-250cm之间', icon: 'none' });
            return false;
          }
        }
        break;
      
      case 'target_weight':
        if (value && value.toString().trim().length > 0) {
          const weight = parseFloat(value);
          if (isNaN(weight) || weight <= 0) {
            wx.showToast({ title: '请输入正确的目标体重', icon: 'none' });
            return false;
          }
          if (weight < 20 || weight > 300) {
            wx.showToast({ title: '目标体重范围应在20-300kg之间', icon: 'none' });
            return false;
          }
        }
        break;
    }
    
    return true;
  }
});
